package com.qwc.blog.controller.back;


import com.qwc.blog.common.validate.IdValid;
import com.qwc.blog.entity.Resource;
import com.qwc.blog.entity.vo.resource.ResourceDto;
import com.qwc.blog.entity.vo.resource.RouterVo;
import com.qwc.blog.security.service.LoginService;
import com.qwc.blog.service.IResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.qwc.blog.common.constant.ResponseConstant.*;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author qwc
 * @since 2021-10-15
 */
@RestController
@RequestMapping("/blog/resource")
public class ResourceController {

    @Autowired
    private IResourceService resourceService;

    @Autowired
    private LoginService loginService;

    @RequestMapping("/routers")
    public ResponseEntity<Object> getRouters() {
        Map<String, Object> map = new HashMap<>(4);
        List<RouterVo> routerVoList = resourceService.getTreeRouter();
        map.put(MESSAGE, SUCCESSFUL_OPERATION);
        map.put(DATA, routerVoList);
        return ResponseEntity.ok(map);
    }

    @GetMapping("/list")
    public ResponseEntity<Object> list(String resName, String status) {
        Map<String, Object> map = new HashMap<>(4);
        List<Resource> resources = resourceService.selectResourceList(resName, status);
        map.put(DATA, resources);
        return ResponseEntity.ok(map);
    }

    @PostMapping
    public ResponseEntity<Object> addResource(@Validated @RequestBody ResourceDto dto) {
        resourceService.addResource(dto.createResource(), loginService.getCurrentUsername());
        return ResponseEntity.ok().build();
    }

    @PutMapping
    public ResponseEntity<Object> updateResource(@Validated(IdValid.class) @RequestBody ResourceDto dto) {
        resourceService.updateResource(dto.createResource(), loginService.getCurrentUsername());
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{resId}")
    public ResponseEntity<Object> getResource(@PathVariable @NotNull(message = "资源Id不能为空") Long resId) {
        Resource byId = resourceService.getById(resId);
        Map<String, Object> map = new HashMap<>(4);
        map.put(DATA, byId);
        return ResponseEntity.ok(map);
    }

    @DeleteMapping("/{resId}")
    public ResponseEntity<Object> deleteResource(@PathVariable @NotNull(message = "资源Id不能为空") Long resId) {
        resourceService.deleteById(resId);
        return ResponseEntity.ok().build();
    }

}
